package com.aly.beanValidate.core.validator;

import java.util.HashMap;
import java.util.Map;

public enum BaseType {
    BOOL("bool", (val) -> {
        if ("true".equalsIgnoreCase(val)
                || "1".equalsIgnoreCase(val)) {
            return true;
        } else if ("false".equalsIgnoreCase(val)
                || "0".equalsIgnoreCase(val)) {
            return false;
        }
        throw new NotThisTypeException();
    }),
    BYTE("byte", Byte::parseByte),
    SHORT("short", Short::parseShort),
    CHAR("char", (val) -> {
        if (val.length() == 1) {
            return val.charAt(0);
        }
        throw new NotThisTypeException();
    }),
    INT("int", Integer::parseInt),
    INT64("int64", Long::parseLong),
    JSON("json", com.alibaba.fastjson.JSON::parse),
    STRING("string", (val) -> val),
    ;

    private final String typeName;
    private final BaseDataTransfer transfer;

    BaseType(String name, BaseDataTransfer transfer) {
        this.typeName = name;
        this.transfer = transfer;
        Holder.typesByName.put(name, this);
    }

    public static BaseType getTypeByName(String name) {
        return Holder.typesByName.get(name);
    }

    public String getTypeName() {
        return typeName;
    }

    public Object transfer(String val) throws Exception {
        return transfer.transferVal(val);
    }

    @Override
    public String toString() {
        return typeName;
    }

    @FunctionalInterface
    public interface BaseDataTransfer {
        Object transferVal(String val) throws NotThisTypeException;
    }

    private static class NotThisTypeException extends Exception {
        NotThisTypeException() {
            super();
        }

        @Override
        public synchronized Throwable fillInStackTrace() {
            return this;
        }
    }

    private static class Holder {
        private static Map<String, BaseType> typesByName = new HashMap<>();

    }
}
